function is_res_expired(res) {
  return res.data.ok == false && res.data.code == 'expired'
}

function login() {
  //每次打开应用，获取一个新的session
  wx.login({
    success: res => {
      if (res.code) {
        console.log('获取session并存储: ' + res.code)

        //Set cookie
        wx.setStorageSync("my-cookie", res.code)

        //获取用户展示信息传到服务器缓存
        wx.getUserInfo({
          success: function (res) {
            console.log('获取用户基本信息: ' + JSON.stringify(res.userInfo))

            wx.setStorageSync('user', res.userInfo)

            //请求服务器缓存用户信息
            module.exports.request(
              config.service.setUser,
              'POST',
              { user: res.userInfo },
              res => {
                console.log('设置用户成功')
              },
              err => {
                alert.showWarn('连接服务器出错')
              }
            )
          }
        })
      }
    }
  })
}

function relogin_and_back_to_index() {
  wx.showModal(
    {
      title: '错误',
      content: '状态已过期,返回首页',
      showCancel: false,
      success: function (res) {

        login()

        wx.reLaunch({
          url: 'index',
        })
      }
    }
  )
}


module.exports = {
  /**
   * 封装发送session
   */
  request(url, method, data, success, fail) {
    wx.request({
      header: {
        'my-cookie': wx.getStorageSync('my-cookie')
      },
      data: data || {},
      url: url,
      method: method,
      success: success,
      fail: fail
    })
  },

  /**
   * 1. 封装cookie请求
   * 2. 处理session过期的情况
   */
  auth_request({
    url = null,
    method = 'POST',
    data = {},
    success = res => {
      console.log('请求成功: ' + res)
    },
    fail = res => {
      console.log('请求失败')
    },
    complete = () => {},
  } = {}) {

    if (url == null) {
      console.error('请求URL不应该为空')
      return
    }

    wx.request({
      url,
      method,
      data,
      fail,
      success: res => {
        if (is_res_expired(res)) {
          console.warn('登录状态过期了')
          relogin_and_back_to_index()
        } else {
          success(res.data)
        }
      },
      header: {
        'my-cookie': wx.getStorageSync('my-cookie')
      },
      complete,
    })
  },


}